import { nextTick, unref } from 'vue'
import { defineStore } from 'pinia'
import { Keys } from '@/constants'
import { router } from '@/router'
import { useRouterPush, useWebsocket } from '@/composables'
import { localStg } from '@/utils'
import { $t } from '@/locales'
import { JBoltApi } from '@/utils/request'
import { ResData } from '@/typings/request'
import { loadThemeSettingFromServer } from '@/store/modules/theme/helpers'
import { useTabStore } from '../tab'
import { useRouteStore } from '../route'
import { clearAuthStorage, getToken, getUserInfo } from './helpers'

interface AuthState {
    /** 用户信息 */
    userInfo: Auth.UserInfo | null
    /** 用户token */
    token: string
    /** 登录的加载状态 */
    loginLoading: boolean
    /** 是否完成了初始化 */
    initDone: boolean

    permissionList: Set<string>

    newTodo:boolean
}

export const useAuthStore = defineStore('auth-store', {
    state: (): AuthState => ({
        userInfo: getUserInfo(),
        token: getToken(),
        loginLoading: false,
        initDone: false,
        permissionList: new Set(),
        newTodo:false
    }),
    getters: {
        /** 是否登录 */
        isLogin(state) {
            return Boolean(state.token)
        }
    },
    actions: {
        /**
         * 通过图形验证码登录
         * @param username - 用户名
         * @param password - 密码
         * @param captcha - 验证码
         * @param keepLogin - 是否保持登录
         */
        async loginByCaptcha(
            username: string,
            password: string,
            captcha: string,
            jbcapkey: string
        ) {
            console.debug('== 执行登录 ==', username, password, captcha, jbcapkey)
            this.loginLoading = true
            try {
                await JBoltApi.tryPost<ResData>('/api/user/auth', {
                    userName: username,
                    password,
                    captcha,
                    jbcapkey
                })
                await this.refreshUserInfo()
                await this.handleActionAfterLogin()
            } finally {
                this.loginLoading = false
            }
        },
        /** 重置auth状态 */
        resetAuthStore() {
            const { toLogin } = useRouterPush(false)
            const { resetTabStore } = useTabStore()
            const { resetRouteStore } = useRouteStore()
            const route = unref(router.currentRoute)

            clearAuthStorage()
            this.userInfo = null
            this.token = ''

            //TODO 下面的要重新处理
            if (route.meta.auth !== false) {
                toLogin()
            }

            nextTick(() => {
                resetTabStore()
                resetRouteStore()
            })
        },
        async init() {
            await this.refreshUserInfo()
            await this.handleActionAfterLogin()
        },
        /**
         * 刷新用户信息
         */
        async refreshUserInfo() {
            await JBoltApi.tryGet<ResData<Auth.UserInfo>>('/api/user/info/mine', null, {
                ignoreMsg: true
            }).then((res) => {
                // 成功后把用户信息存储到缓存中
                localStg.set(Keys.USER, res.data)
                // 更新状态
                this.userInfo = res.data!
                this.initDone = true
            })
        },

        /**
         * 刷新权限列表
         */
        async refreshPermissionList() {
            console.debug('加载权限列表')
            const res = await JBoltApi.tryGet<ResData<string>>(
                '/api/user/permission/keys'
            )
            if (res.data) {
                this.permissionList = new Set(res.data)
            } else {
                this.permissionList = new Set()
            }
        },

        /**
         * 处理登录后成功或失败的逻辑
         */
        async handleActionAfterLogin() {
            const route = useRouteStore()
            const { toLoginRedirect } = useRouterPush(false)

            console.debug('登录成功')
            await this.refreshPermissionList()
            await route.initAuthRoute()

            // 跳转登录后的地址
            toLoginRedirect()

            // 登录成功弹出欢迎提示
            if (route.isInitAuthRoute) {
                window.$notification?.success({
                    title: $t('page.login.common.loginSuccess'),
                    content: $t('page.login.common.welcomeBack', {
                        userName: this.userInfo!.username
                    }),
                    duration: 3000
                })
            }

            //加载个人主题设置
            loadThemeSettingFromServer()
            //初始化websocket
            useWebsocket().init()
        },
        /**
         * 检测是否有某个权限
         * @param permissionKey，权限key，也就是route的name
         */
        checkHasPermission(permissionKey: string | string[]) {
            if (Array.isArray(permissionKey)) {
                return permissionKey.some((key) => this.permissionList.has(key))
            }
            return this.permissionList.has(permissionKey)
        }
    }
})
